package org.simplecrm.repository.region;

import org.simplecrm.domain.region.Region;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by Oleksandr_Terekh on 9/4/2014.
 */
@Repository("regionDAO")
public class RegionJdbcDAO implements RegionDAO {

    private static final Logger LOGGER = LoggerFactory.getLogger(RegionJdbcDAO.class);

    private static final String SELECT_ALL = "SELECT * FROM region";

    private DataSource ds;

    @Autowired
    public RegionJdbcDAO(DataSource ds) {
        this.ds = ds;
    }

    @Override
    public List<Region> getAllRegions() {

        List<Region> regions = new LinkedList<>();

        try (Connection con = ds.getConnection();
             PreparedStatement statement = con.prepareStatement(SELECT_ALL,
                     ResultSet.TYPE_SCROLL_INSENSITIVE,
                     ResultSet.CONCUR_UPDATABLE);
             ResultSet resultset = statement.executeQuery()) {

            while (resultset.next()) {

                Region region = null;

                int id = resultset.getInt(REGION_ID_FIELD);
                String name = resultset.getString(REGION_NAME_FIELD);

                region = new Region(id, name);

                regions.add(region);
            }

        } catch (SQLException ex) {
            LOGGER.error(ex.toString(), ex);
            regions = null;
        }

        return regions;
    }
}
